import { relationalStore } from '@kit.ArkData'
import { BookRepository } from './repositories/BookRepository'
import { ChapterRepository } from './repositories/ChapterRepository'
import { PluginRepository } from './repositories/PluginRepository'
import { RemoteRepository } from './repositories/RemoteRepository'

class DataBase {
  private _book: BookRepository | undefined
  private _remote: RemoteRepository | undefined
  private _plugin: PluginRepository | undefined
  private _chapter: ChapterRepository | undefined

  get book(): BookRepository {return this._book!}
  get plugin(): PluginRepository {return this._plugin!}
  get remote(): RemoteRepository {return this._remote!}
  get chapter(): ChapterRepository {return this._chapter!}

  tables: string[] = [
    // 远程仓库表
    `CREATE TABLE IF NOT EXISTS remote (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      host TEXT NOT NULL UNIQUE
    )`,
    // 插件表
    `CREATE TABLE IF NOT EXISTS plugin (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      remote_id INTEGER,
      icon TEXT,
      host TEXT NOT NULL,
      name TEXT NOT NULL,
      version TEXT,
      type TEXT,
      data TEXT,
      create_at INTEGER,
      update_at INTEGER,
      FOREIGN KEY (remote_id) REFERENCES remote(id)
    )`,
    // 书籍表
    `CREATE TABLE IF NOT EXISTS book (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      plugin_id INTEGER,
      type TEXT,

      name TEXT NOT NULL,
      url TEXT NOT NULL,
      cover TEXT,
      intro TEXT,
      author TEXT,
      tags TEXT,
      last_chapter_name TEXT,

      in_store INTEGER NOT NULL DEFAULT 0,
      last_read_chapter_id INTEGER NOT NULL DEFAULT 0,
      last_read_chapter_page INTEGER NOT NULL DEFAULT 0,

      create_at INTEGER,
      update_at INTEGER,
      FOREIGN KEY (plugin_id) REFERENCES plugin(id)
    )`,
    // 章节表
    `CREATE TABLE IF NOT EXISTS chapter (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      plugin_id INTEGER,
      book_id INTEGER,

      name TEXT NOT NULL,
      url TEXT NOT NULL,
      content TEXT,
      group_name TEXT,
      is_read INTEGER NOT NULL DEFAULT 0,

      create_at INTEGER,
      update_at INTEGER,
      FOREIGN KEY (plugin_id) REFERENCES plugin(id),
      FOREIGN KEY (book_id) REFERENCES book(id)
    )`
  ]

  async init(context: any, name: string = "default") {
    const db = await relationalStore.getRdbStore(context, { name, securityLevel: relationalStore.SecurityLevel.S1 })
    for (let i = 0; i < this.tables.length; i++) {
      await db.executeSql(this.tables[i])
    }
    this._book = new BookRepository(db)
    this._remote = new RemoteRepository(db)
    this._plugin = new PluginRepository(db)
    this._chapter = new ChapterRepository(db)
  }

}


export default new DataBase()